package com.fintech.pangu.security.oauth2.sso.client.endpoint;

import com.alibaba.fastjson.JSON;
import com.fintech.pangu.framework.endpoint.PanGuFrameworkEndpoint;
import com.fintech.pangu.security.oauth2.sso.client.model.dto.UserInfoDto;
import com.fintech.pangu.security.oauth2.sso.client.model.vo.UserInfoResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 * @Description:
 */
@PanGuFrameworkEndpoint
@Api(tags = "获取已登录的用户详情")
public class OAuth2UserDetailEndpoint {

    /**
     * 单点登录成功后跳转到loginSuccess，页面中将userInfo告知父页面
     * @param model
     * @return
     */
    @ApiIgnore
    @RequestMapping(value = "/oauthUserDetails")
    public String oauthUserDetail(Model model) {
        OAuth2Authentication auth2Authentication = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication();
        Map<String, Object> userDetails = (Map<String, Object>) auth2Authentication.getUserAuthentication().getDetails();

        UserInfoDto userInfoVO = new UserInfoDto();
        userInfoVO.setUserCode((String) auth2Authentication.getPrincipal());
        //userInfoVO.setUserName((String) userDetails.get("loginName"));
        userInfoVO.setUserName((String) auth2Authentication.getPrincipal()); // check_token后返回内容中没有details信息
        model.addAttribute("userInfo",
                JSON.toJSONString(UserInfoResponse
                        .builder()
                        .userInfo(userInfoVO)
                        .build()));
        return "loginSuccess";
    }

    /**
     * 获取用户信息接口
     * @return
     */
    @ApiOperation(value = "获取用户信息", notes = "获取已登录认证的用户信息详情", response = UserInfoResponse.class)
    @RequestMapping(value = "/userInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public UserInfoResponse getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        UserInfoDto userInfoVO = new UserInfoDto();
        userInfoVO.setUserName((String) authentication.getPrincipal());

        return UserInfoResponse
                .builder()
                .userInfo(userInfoVO)
                .build();
    }
}
